
package com.scott.itcast.thread.lesson17;

/**
 * 多线程共享数据 设计4个线程，其中两个线程每次对j增加1，另外两个线程对j每次减少1。写出程序
 * 多线程共享数据 设计4个线程，其中两个线程每次对j增加1，另外两个线程对j每次减少1。写出程序
 * 方法4-4
 * 
 */
public class MultiThreadShareData {
	private static  ShareData share = new ShareData();
	
	public static void main(String args[]) {
		
		//final ShareData share = new ShareData();
		
		//在线程A中要做的事情
		RunnableA runnableA = new RunnableA(share);
		
		//在线程B中要做的事情
		RunnableB runnableB = new RunnableB(share);
		
		
		for (int i = 0; i < 2; i++) {
			//启动线程A  把runnableA交给线程去运行
			new Thread(runnableA).start();
			
			//启动线程B 把runnableB交给线程去运行
			new Thread(runnableB).start();
		}
	}
	
	
	
}

class RunnableA implements Runnable{

	private ShareData share;
	public RunnableA(ShareData share){
		this.share =share;
	}
	
	//增加
	public void run() {
		share.inc();
	}
	
}

class RunnableB implements Runnable{

	private ShareData share;
	public RunnableB(ShareData share){
		this.share =share;
	}
	
	//减少
	public void run() {
		share.dec();
	}
	
}


//共享的数据
class ShareData{
	private int j =0;
	
	//增加
	public synchronized void inc() {
		for(int i =0; i<100;i++){
			j++;
			System.out.println(Thread.currentThread().getName() + "-inc增加:" + j);
		}
	}
	
	//减少
	public synchronized void dec() {
		for(int i =0;i<100;i++){
			j--;
			System.out.println(Thread.currentThread().getName() + "-dec减少:" + j);
		}
	}
}
